#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Web浏览器组件
提供网页浏览功能，支持前进、后退、刷新等操作
"""

from PyQt5.QtWidgets import (QWidget, QVBoxLayout, QHBoxLayout, QPushButton,
                             QLineEdit, QLabel, QProgressBar, QToolBar, QAction)
from PyQt5.QtWebEngineWidgets import QWebEngineView, QWebEnginePage, QWebEngineSettings
from PyQt5.QtCore import Qt, QUrl, pyqtSignal
from PyQt5.QtGui import QIcon, QFont
import webbrowser

class WebBrowser(QWidget):
    """Web浏览器组件"""
    
    # 信号定义
    url_changed = pyqtSignal(str)  # URL变化信号
    title_changed = pyqtSignal(str)  # 标题变化信号
    load_finished = pyqtSignal()  # 加载完成信号
    load_progress = pyqtSignal(int)  # 加载进度信号
    
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setup_ui()
        self.setup_connections()
        
    def setup_ui(self):
        """设置UI"""
        layout = QVBoxLayout(self)
        layout.setContentsMargins(0, 0, 0, 0)
        
        # 创建工具栏
        self.toolbar = QToolBar()
        self.toolbar.setMovable(False)
        layout.addWidget(self.toolbar)
        
        # 添加工具栏按钮
        self.setup_toolbar()
        
        # 创建Web视图
        self.web_view = QWebEngineView()
        layout.addWidget(self.web_view)
        
        # 创建状态栏
        self.setup_status_bar(layout)
        
    def setup_toolbar(self):
        """设置工具栏"""
        # 后退按钮
        self.back_action = QAction("◀", self)
        self.back_action.setToolTip("后退")
        self.back_action.triggered.connect(self.go_back)
        self.toolbar.addAction(self.back_action)
        
        # 前进按钮
        self.forward_action = QAction("▶", self)
        self.forward_action.setToolTip("前进")
        self.forward_action.triggered.connect(self.go_forward)
        self.toolbar.addAction(self.forward_action)
        
        # 刷新按钮
        self.reload_action = QAction("🔄", self)
        self.reload_action.setToolTip("刷新")
        self.reload_action.triggered.connect(self.reload)
        self.toolbar.addAction(self.reload_action)
        
        # 停止按钮
        self.stop_action = QAction("⏹", self)
        self.stop_action.setToolTip("停止")
        self.stop_action.triggered.connect(self.stop)
        self.toolbar.addAction(self.stop_action)
        
        # 分隔符
        self.toolbar.addSeparator()
        
        # 地址栏
        self.url_bar = QLineEdit()
        self.url_bar.setPlaceholderText("输入网址或搜索内容...")
        self.url_bar.returnPressed.connect(self.navigate_to_url)
        self.toolbar.addWidget(QLabel("地址:"))
        self.toolbar.addWidget(self.url_bar)
        
        # 转到按钮
        self.go_button = QPushButton("转到")
        self.go_button.clicked.connect(self.navigate_to_url)
        self.toolbar.addWidget(self.go_button)
        
        # 分隔符
        self.toolbar.addSeparator()
        
        # 外部浏览器按钮
        self.external_action = QAction("🌐", self)
        self.external_action.setToolTip("在外部浏览器中打开")
        self.external_action.triggered.connect(self.open_external)
        self.toolbar.addAction(self.external_action)
        
    def setup_status_bar(self, layout):
        """设置状态栏"""
        status_layout = QHBoxLayout()
        
        # 状态标签
        self.status_label = QLabel("就绪")
        status_layout.addWidget(self.status_label)
        
        # 进度条
        self.progress_bar = QProgressBar()
        self.progress_bar.setVisible(False)
        self.progress_bar.setMaximumWidth(200)
        status_layout.addWidget(self.progress_bar)
        
        # 页面信息
        self.page_info = QLabel("")
        status_layout.addWidget(self.page_info)
        
        status_layout.addStretch()
        
        layout.addLayout(status_layout)
        
    def setup_connections(self):
        """设置信号连接"""
        # Web视图信号连接
        self.web_view.urlChanged.connect(self.on_url_changed)
        self.web_view.titleChanged.connect(self.on_title_changed)
        self.web_view.loadFinished.connect(self.on_load_finished)
        self.web_view.loadProgress.connect(self.on_load_progress)
        
    def navigate_to_url(self):
        """导航到指定URL"""
        url_text = self.url_bar.text().strip()
        if not url_text:
            return
            
        # 如果输入的不是完整URL，则添加协议
        if not url_text.startswith(('http://', 'https://')):
            if '.' in url_text and ' ' not in url_text:
                url_text = 'https://' + url_text
            else:
                # 作为搜索查询处理
                url_text = f'https://www.google.com/search?q={url_text}'
        
        self.load_url(url_text)
        
    def load_url(self, url):
        """加载URL"""
        try:
            qurl = QUrl(url)
            self.web_view.setUrl(qurl)
            self.status_label.setText(f"正在加载: {url}")
        except Exception as e:
            self.status_label.setText(f"加载失败: {str(e)}")
            
    def go_back(self):
        """后退"""
        if self.web_view.history().canGoBack():
            self.web_view.back()
            
    def go_forward(self):
        """前进"""
        if self.web_view.history().canGoForward():
            self.web_view.forward()
            
    def reload(self):
        """刷新页面"""
        self.web_view.reload()
        
    def stop(self):
        """停止加载"""
        self.web_view.stop()
        
    def open_external(self):
        """在外部浏览器中打开"""
        current_url = self.web_view.url().toString()
        if current_url:
            webbrowser.open(current_url)
            
    def on_url_changed(self, url):
        """URL变化处理"""
        url_str = url.toString()
        self.url_bar.setText(url_str)
        self.url_changed.emit(url_str)
        
    def on_title_changed(self, title):
        """标题变化处理"""
        self.title_changed.emit(title)
        
    def on_load_finished(self, success):
        """加载完成处理"""
        self.progress_bar.setVisible(False)
        if success:
            self.status_label.setText("加载完成")
            self.load_finished.emit()
        else:
            self.status_label.setText("加载失败")
            
    def on_load_progress(self, progress):
        """加载进度处理"""
        self.progress_bar.setVisible(progress < 100)
        self.progress_bar.setValue(progress)
        self.load_progress.emit(progress)
        
    def get_current_url(self):
        """获取当前URL"""
        return self.web_view.url().toString()
        
    def get_current_title(self):
        """获取当前标题"""
        return self.web_view.title()
        
    def set_zoom_factor(self, factor):
        """设置缩放因子"""
        self.web_view.setZoomFactor(factor)
        
    def get_zoom_factor(self):
        """获取缩放因子"""
        return self.web_view.zoomFactor()
        
    def zoom_in(self):
        """放大"""
        current_zoom = self.get_zoom_factor()
        self.set_zoom_factor(min(current_zoom * 1.2, 3.0))
        
    def zoom_out(self):
        """缩小"""
        current_zoom = self.get_zoom_factor()
        self.set_zoom_factor(max(current_zoom / 1.2, 0.5))
        
    def reset_zoom(self):
        """重置缩放"""
        self.set_zoom_factor(1.0)
        
    def execute_javascript(self, script):
        """执行JavaScript代码"""
        self.web_view.page().runJavaScript(script)
        
    def get_page_source(self):
        """获取页面源代码"""
        def handle_source(source):
            return source
            
        self.web_view.page().toHtml(handle_source)
        
    def find_text(self, text):
        """在页面中查找文本"""
        script = f"window.find('{text}');"
        self.execute_javascript(script)
        
    def clear_history(self):
        """清除历史记录"""
        self.web_view.history().clear()
        
    def can_go_back(self):
        """是否可以后退"""
        return self.web_view.history().canGoBack()
        
    def can_go_forward(self):
        """是否可以前进"""
        return self.web_view.history().canGoForward()
        
    def update_toolbar_state(self):
        """更新工具栏状态"""
        self.back_action.setEnabled(self.can_go_back())
        self.forward_action.setEnabled(self.can_go_forward())
        
    def set_user_agent(self, user_agent):
        """设置用户代理"""
        profile = self.web_view.page().profile()
        profile.setHttpUserAgent(user_agent)
        
    def enable_javascript(self, enabled=True):
        """启用/禁用JavaScript"""
        settings = self.web_view.settings()
        settings.setAttribute(QWebEngineSettings.JavascriptEnabled, enabled)
        
    def enable_plugins(self, enabled=True):
        """启用/禁用插件"""
        settings = self.web_view.settings()
        settings.setAttribute(QWebEngineSettings.PluginsEnabled, enabled)
        
    def set_cache_size(self, size_mb):
        """设置缓存大小"""
        profile = self.web_view.page().profile()
        profile.setHttpCacheMaximumSize(size_mb * 1024 * 1024)
        
    def clear_cache(self):
        """清除缓存"""
        profile = self.web_view.page().profile()
        profile.clearHttpCache()
        
    def clear_cookies(self):
        """清除Cookie"""
        profile = self.web_view.page().profile()
        profile.cookieStore().deleteAllCookies()
